<template>
  <div class="relationpages">
    <div class="headerbox">
      <div class="headerboxLeft">
        <el-form ref="filterForm" v-model="filterForm" inline>
          <el-form-item label="页面类型">
            <el-select v-model="typevalue" v-selectLoadMore="selectLoadMore" clearable placeholder="请选择">
              <el-option
                v-for="item in filterForm.pageTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学段">
            <el-select v-model="sectionvalue" clearable placeholder="请选择">
              <el-option
                v-for="item in filterForm.section"
                :key="item.code"
                :label="item.name"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="页面名称">
            <el-input v-model="pageFormData.pageName" placeholder="请输入页面名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="serchTable">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="headerboxRight">
        <el-button type="warning" @click="goBackPrev">返回</el-button>
        <el-button type="success" @click="saveChoosePage">保存</el-button>
      </div>
    </div>
    <div class="pagedata">
      <el-table
        ref="multipleTable"
        :data="pagesData"
        tooltip-effect="dark"
        style="width: 100%; margin-bottom: 20px"
        @select="handleSelectionChange"
        @select-all="handleSeleAll"
        :row-key="getRowKeys">
        <el-table-column type="selection" :reserve-selection="true" width="55" :selectable="selectedDisabled">
        </el-table-column>
        <el-table-column prop="id" label="ID"> </el-table-column>
        <el-table-column prop="name" label="页面名称"> </el-table-column>
        <el-table-column prop="alias" label="页面标识"> </el-table-column>
        <el-table-column label="版本号">
          <template slot-scope="scope">
            <el-tag type="danger">{{ scope.row.version }}</el-tag>
            <el-button size="mini" @click="showVersion(scope.row, scope.$index)">切换</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="newsVersion" label="最新版本"> </el-table-column>
        <el-table-column prop="note" label="备注"> </el-table-column>
        <el-table-column prop="updateTime" label="更新时间"> </el-table-column>
        <el-table-column prop="statusName" label="发布状态"> </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageFormData.pageSize"
        :current-page="pageFormData.pageNum"
        @current-change="SetPage">
      </el-pagination>
    </div>
    <el-dialog title="选择版本" :visible.sync="dialogTableVisible">
      <el-table :data="gridData" style="margin-bottom: 20px" :row-class-name="tableRowClassName">
        <el-table-column property="id" label="ID"></el-table-column>
        <el-table-column property="version" label="版本"></el-table-column>
        <el-table-column property="name" label="名字"></el-table-column>
        <el-table-column property="note" label="备注"></el-table-column>
        <el-table-column property="updateTime" label="更新时间"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="small" plain @click="changeVersion(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="vtotal"
        :page-size="verformdata.pageSize"
        :current-page="verformdata.pageNum"
        @current-change="SetVersionPage">
      </el-pagination>
    </el-dialog>
  </div>
</template>
<script>
import {
  getPageList,
  getTypeList,
  getSection,
  saveRelationPages,
  pageversionByTemplate,
  getPageDataList,
} from "@/api/basisMG";
export default {
  data() {
    return {
      multipleSelection: [], // 选中某一行
      multipleSelectionAll: [], // 全选
      filterForm: {
        pageTypeList: [],
        section: [],
      },
      pagesData: [],
      gridData: [],
      pageFormData: {
        appType: "",
        pageType: "",
        tags: "",
        pageNum: 1,
        pageSize: 10,
        pageName: ''
      },
      formData: {
        type: 1,
        productType: "",
        pageNum: 1,
        pageSize: 10,
      },
      typevalue: "",
      sectionvalue: "",
      formsecdata: {
        id: "section",
        codes: "",
      },
      relaformdata: {
        templateId: "",
        pageDataId: "",
      },
      verformdata: {
        pageId: "",
        pageNum: 1,
        pageSize: 10,
      },
      verdatalist: [],
      vtotal: 0,
      veridarr: [], // 选中页面id基础数组
      dialogTableVisible: false,
      currentVersion: "", //当前版本
      currentIndex: "",
      total: 0,
      typeTotal: 0
    };
  },
  async mounted() {
    this.getTypeList();
    this.getSectionList();
    if (this.$route.query.id) {
      await this.pageversionByTemplate();
    }
    this.getPageList();
  },
  methods: {
    // 下拉加载更多
    selectLoadMore () {
      this.formData.pageSize = this.formData.pageSize + 1;
      console.log(this.typeTotal, 'typeTotal-----');
      if (this.formData.pageSize > this.typeTotal) return
      this.getTypeList()
    },
    // 根据条件判断是否被禁选
    selectedDisabled(row, index) {
      if (row.version == "" || row.version == undefined) {
        return false; //不可勾选
      } else {
        return true; //可勾选
      }
    },
    // 分页
    SetPage(e) {
      this.pageFormData.pageNum = e;
      this.getPageList();
    },
    // 版本分页
    SetVersionPage(e) {
      this.verformdata.pageNum = e;
      this.getPageDataList();
    },
    serchTable() {
      this.pageFormData.pageNum = 1;
      this.pageFormData.pageType = this.typevalue;
      if (this.sectionvalue) {
        this.pageFormData.tags = "section-" + this.sectionvalue;
      }
      this.getPageList();
    },
    goBackPrev() {
      // this.$router.go(-1);
      this.$router.push({
        path: './templateList',
        query: {
          protype: this.$route.query.type
        }
      })
    },
    //获取页面类型
    async getTypeList() {
      const res = await getTypeList(this.formData);
      if (res.code === '200') {
        this.filterForm.pageTypeList = res.data.content;
        this.typeTotal = res.data.total;
      } else {
        this.filterForm.pageTypeList = [];
      }
    },
    //获取学段
    async getSectionList() {
      const res = await getSection(this.formsecdata);
      this.filterForm.section = res.data.tagEnumVoList;
    },
    // 获取页面列表
    async getPageList() {
      this.pageFormData.appType = this.$route.query.type;
      const res = await getPageList(this.pageFormData);
      if (res.data) {
        this.pagesData = [];
        res.data.content.forEach((item) => {
          this.pagesData.push({ ...item, newId: item.id, newsVersion: item.version });
        });
        this.total = res.data.total;
        for (let i = 0; i < this.pagesData.length; i++) {
          for (let j = 0; j < this.veridarr.length; j++) {
            if (this.veridarr[j].pageId == this.pagesData[i].id) {
              this.$refs.multipleTable.toggleRowSelection(this.pagesData[i]);
              this.pagesData[i].version = this.veridarr[j].version;
            }
          }
        }
      } else {
        this.pagesData = [];
      }
    },
    // 获取页面数据列表
    async getPageDataList() {
      const res = await getPageDataList(this.verformdata);
      if (res.data) {
        this.gridData = res.data.content;
        this.vtotal = res.data.total;
      } else {
        this.gridData = [];
      }
    },
    // 版本信息列表
    showVersion(e, index) {
      this.resetDtata();
      this.dialogTableVisible = true;
      this.verformdata.pageId = e.id;
      this.getPageDataList();
      this.currentVersion = e.version;
      this.currentIndex = index;
    },
    // 重置列表
    resetDtata() {
      this.verformdata = {
        pageId: "",
        pageNum: 1,
        pageSize: 10,
      };
    },
    // 切换版本
    changeVersion(e) {
      if (this.currentVersion != e.version) {
        this.pagesData[this.currentIndex].version = e.version;
        // this.pagesData[this.currentIndex].pageDataId = e.id;
        const chageVerId = this.pagesData[this.currentIndex].newId;
        const chageVer = this.veridarr.filter((item) => item.newId == chageVerId);
        if (chageVer.length > 0) {
          this.veridarr = this.veridarr.map((item) => {
            if (chageVerId == item.newId) {
              return { ...item, pageDataId: e.id };
            } else {
              return { ...item };
            }
          });
        }
        this.dialogTableVisible = false;
      } else {
        this.$message({
          type: "info",
          message: "您选择的版本和当前版本一致！",
        });
        this.dialogTableVisible = false;
      }
    },
    // 选中某一行
    handleSelectionChange(val, row) {
      this.multipleSelection = val;
      const checkedDData = val.filter((item) => item.id === row.id);
      if (checkedDData.length > 0) {
        let index = this.veridarr.indexOf(row);
        if (index == -1) {
          this.veridarr.push(row);
        }
      } else {
        this.veridarr = this.veridarr.filter((item) => item.newId !== row.newId);
      }
    },
    // 全选/取消全选
    handleSeleAll(selection) {
      this.multipleSelectionAll = selection;
      if (selection.length != 0) {
        this.veridarr = selection;
      } else {
        this.pagesData.forEach((item) => {
          this.veridarr = this.veridarr.filter((ite) => ite.newId !== item.newId);
        });
      }
    },
    //保存选择页面
    saveChoosePage() {
      // console.log(this.veridarr, "this.veridarr");
      if (this.veridarr.length <= 0) {
        this.$message.error("请选择页面！");
      } else {
        this.$confirm("确定要保存选择的页面吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            const newArr = [];
            this.veridarr.forEach((item) => {
              newArr.push(item.pageDataId);
            });
            this.relaformdata.pageDataId = newArr.join(",");
            this.relaformdata.templateId = this.$route.query.id;
            const data = await saveRelationPages(this.relaformdata);
            if (data.code != 200) return this.$message.error("操作失败请稍后重试");
            this.$message({
              type: "success",
              message: "保存成功!",
            });
            // this.$router.go(-1);
            this.$router.push({
              path: './templateList',
              query: {
                protype: this.$route.query.type
              }
            })
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消选择",
            });
          });
      }
    },
    //获取最新版本已关联页面的信息
    async pageversionByTemplate() {
      const res = await pageversionByTemplate({ id: this.$route.query.id });
      this.verdatalist = res.data;
      this.veridarr = [];
      if (res.data) {
        this.verdatalist.forEach((item) => {
          this.veridarr.push({ ...item, pageDataId: item.id, newId: item.pageId });
        });
      }
    },
    getRowKeys(row) {
      if (row.id) {
        //判断条件，根据自己的项目进行添加
        return row.id; //一般是你选择项的id
      }
    },
    tableRowClassName(row) {
      if (row.row.version === this.currentVersion) {
        return "success-row";
      }
      return "";
    }
  },
};
</script>
<style lang="scss">
.relationpages {
  padding: 20px;
  .headerbox {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .el-table .success-row {
    background: #f0f9eb;
  }
}
</style>
